﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Taobao.Framework;
using Taobao.Framework.WinForm;
using System.Configuration;
using System.Threading;

namespace Taobao.GatherInform
{
    public partial class GatherForm : Form
    {
        public const string UseAutoGatherKey = "UseAutoGather";
        public const string AutoGatherKeyUrlKey = "AutoGatherKeyUrl";
        public const string CloseWindowAfterCompleteKey = "CloseWindowAfterComplete";
        public const string DBStatusControKey = "DBStatusControl";
        public const string DBStatusCheckIntervalKey = "DBStatusCheckInterval";

        protected const int DefaultDBStatusCheckInterval = 10;

        protected readonly bool DBStatusControl = ConfigurationManager.AppSettings[DBStatusControKey] == "true";

        GatherInformationProcessor Processor { get; set; }

        public GatherForm()
        {
            InitializeComponent();
        }

        private void StartButton_Click(object sender, EventArgs e)
        {
            GatherInformation(GetQueryFilter());
        }

        private void GatherForm_Load(object sender, EventArgs e)
        {
            writeTextBoxFun = SetTextBoxText;
            if (DBStatusControl)
            {
                StartButton.Enabled = false;
                DetailSettingButton.Enabled = false;
                Text = "抓取信息--DB 控制运行状态";
                int interval = 0;
                Int32.TryParse(ConfigurationManager.AppSettings[DBStatusCheckIntervalKey], out interval);
                if (interval <= 0)
                {
                    interval = 1000*60;
                }
                var timer = new System.Timers.Timer(interval*60*1000);
                timer.AutoReset = true;
                timer.Enabled = true;
                timer.Interval = interval * 60 * 1000;
                timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
                timer.Start();
            }
            else
            {
                StartButton.Enabled = true;
                DetailSettingButton.Enabled = true;
                Text = "抓取信息";
            }

            splitContainer1.SplitterDistance = DetailSettingPanel.Visible ? 182 : 76;
            BindFilters();

            if (ConfigurationManager.AppSettings[UseAutoGatherKey] == "true")
            {
                DoAutoGather();
            }
        }

        void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            bool needGather = false;
            using (var ObjectContext = new Model.taobaogatherEntities())
            {
                try
                {
                    var shop = ObjectContext.Shops.SingleOrDefault();
                    needGather = shop.Status == GatherInformationProcessor.UpdateStatus_Waiting;
                }
                catch { }
            }
            if (needGather)
            {
                DoAutoGather();
            }
        }

        delegate void WriteFunc(string value);
        WriteFunc writeTextBoxFun;

        protected void SetTextBoxText(string text)
        {
            TitleFilterTextBox.Text = text; 
        }
        protected void DoAutoGather()
        {
            Thread.Sleep(1000);
            string gatherKey = GetQueryKey();
            if (TitleFilterTextBox.InvokeRequired)
            {
                TitleFilterTextBox.BeginInvoke(writeTextBoxFun, gatherKey);
            }
            else {
                TitleFilterTextBox.Text = gatherKey;
            }
            //TitleFilterTextBox.Text = gatherKey;
            Query query = GetQueryFilter();
            query.Title = gatherKey;
            GatherInformation(query);
        }
         

        void Processor_ProcessCompleted(object sender, EventArgs e)
        {
            if (ConfigurationManager.AppSettings[UseAutoGatherKey] == "true" && ConfigurationManager.AppSettings[CloseWindowAfterCompleteKey] == "true")
            {
                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
        }

        private void GatherForm_FormClosed(object sender, FormClosedEventArgs e)
        {

        }

        private void GatherForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (Processor != null)
                {
                    Processor.UpdateShopStatus(GatherInformationProcessor.UpdateStatus_End);
                    Processor.End();
                }
                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
            catch
            { }
        }

        private void DetailSettingButton_Click(object sender, EventArgs e)
        {
            DetailSettingPanel.Visible = !DetailSettingPanel.Visible;
            if (DetailSettingPanel.Visible)
            {
                DetailSettingButton.Text = "隐藏详细设置";
            }
            else
            {
                DetailSettingButton.Text = "显示详细设置";
            }
            splitContainer1.SplitterDistance = DetailSettingPanel.Visible ? 182 : 76;
        }

        protected void GatherInformation(Query query)
        {
            Processor = new GatherInformationProcessor(new TextBoxWriter(OutputTextBox));
            Processor.ProcessCompleted += new EventHandler<EventArgs>(Processor_ProcessCompleted);
            Console.SetOut(Processor.TextWriter);
            if (TitleFilterTextBox.Text.Trim() == string.Empty)
            {
                MessageBox.Show("请输入关键字后再搜索！");
                return;
            }
            Processor.Query = query;
            Processor.Start();
        }

        protected void BindFilters()
        {
            NewStatusComboBox.Items.Clear();
            NewStatusComboBox.ValueMember = "Value";
            NewStatusComboBox.DisplayMember = "Text";
            NewStatusComboBox.DataSource = new List<dynamic>() {
                new {Text="所有",Value=-1},
                new {Text="全新",Value=1},
                new {Text="二手",Value=0},
                new {Text="闲置",Value=2}
            };
            NewStatusComboBox.SelectedIndex = 0;


            DiscountComboBox.Items.Clear();
            DiscountComboBox.ValueMember = "Value";
            DiscountComboBox.DisplayMember = "Text";
            DiscountComboBox.DataSource = new List<dynamic>() {
                new {Text="所有",Value=-1},
                new {Text="有折扣",Value=1},
                new {Text="无折扣",Value=0}
            };
            DiscountComboBox.SelectedIndex = 0;


            WangWangStatusomboBox.Items.Clear();
            WangWangStatusomboBox.ValueMember = "Value";
            WangWangStatusomboBox.DisplayMember = "Text";
            WangWangStatusomboBox.DataSource = new List<dynamic>() {
                new {Text="所有",Value=-1},
                new {Text="在线",Value=1},
                new {Text="离线",Value=0}
            };
            WangWangStatusomboBox.SelectedIndex = 0;

            VirtualComboBox.Items.Clear();
            VirtualComboBox.ValueMember = "Value";
            VirtualComboBox.DisplayMember = "Text";
            VirtualComboBox.DataSource = new List<dynamic>() {
                new {Text="所有商品",Value=-1},
                new {Text="虚拟商品",Value=1},
                new {Text="非虚拟商品",Value=0}
            };
            VirtualComboBox.SelectedIndex = 0;

            WarrantyComboBox.Items.Clear();
            WarrantyComboBox.ValueMember = "Value";
            WarrantyComboBox.DisplayMember = "Text";
            WarrantyComboBox.DataSource = new List<dynamic>() {
                new {Text="所有",Value=-1},
                new {Text="假一赔三",Value=2},
                new {Text="7天无理由退换货",Value=4}
            };
            WarrantyComboBox.SelectedIndex = 0;
        }

        public string GetQueryKey()
        {
            Top.Api.Util.WebUtils webUtils = new Top.Api.Util.WebUtils();
            string queryKeyUrl = ConfigurationManager.AppSettings[AutoGatherKeyUrlKey];
            Dictionary<string, string> queryParameters = new Dictionary<string, string>();
            return webUtils.DoGet(queryKeyUrl, queryParameters);
        }

        protected Query GetQueryFilter()
        {
            Query query = new Query();
            query.Title = string.IsNullOrEmpty(TitleFilterTextBox.Text.Trim()) ? null : TitleFilterTextBox.Text.Trim();
            query.Nicks = string.IsNullOrEmpty(this.NickTextBox.Text.Trim()) ? null : NickTextBox.Text.Trim();


            query.City = string.IsNullOrEmpty(this.CityTextBox.Text.Trim()) ? null : CityTextBox.Text.Trim();

            query.State = string.IsNullOrEmpty(this.StateTextBox.Text.Trim()) ? null : StateTextBox.Text.Trim();

            long startPrice = 0;
            long endPrice = 0;
            if(long.TryParse(StartPriceTextBox.Text.Trim(),out startPrice)
                && long.TryParse(this.EndPriceTextBox.Text.Trim(), out endPrice))
            {
                query.StartPrice = startPrice;
                query.EndPrice =endPrice;
            }


            var auctionFlag = (int)VirtualComboBox.SelectedValue;
            if (auctionFlag == 1)
                query.AuctionFlag = true;
            else if (auctionFlag == 0)
                query.AuctionFlag = false;
            else
                query.AuctionFlag = null;


            var discount = (int)this.DiscountComboBox.SelectedValue;
            if (discount == 1)
                query.HasDiscount = true;
            else if (discount == 0)
                query.HasDiscount = false;
            else
                query.HasDiscount = null;

            var wwStatus = (int)this.WangWangStatusomboBox.SelectedValue;
            if (wwStatus == 1)
                query.WWStatus = true;
            else if (wwStatus == 0)
                query.WWStatus = false;
            else
                query.WWStatus = null;


            var newly = (int)this.NewStatusComboBox.SelectedValue;
            if (newly == 1)
                query.StuffStatus = "new";
            else if (newly == 0)
                query.StuffStatus = "second";
            else if (newly == 2)
                query.StuffStatus = "unused";
            else
                query.StuffStatus = null;

            var promotedSevice = (int)this.WarrantyComboBox.SelectedValue;
            if (newly == 2)
                query.PromotedService = "2";
            else if (newly == 4)
                query.PromotedService = "4"; 
            else
                query.PromotedService = null;

            return query;
        }
    }
}
